/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.menosehmais.framework.presentation;

import br.com.caelum.vraptor.Result;
import static br.com.caelum.vraptor.view.Results.json;
import java.util.List;

/**
 *
 * @author Rafael Quintino
 */
public class RestResponseController<T> {

    protected final Result result;

    public RestResponseController( Result result ) {
        this.result = result;
    }

    public void throwsExceptionForRollback() {
        result.on(RuntimeException.class).forwardTo(getClass()).error();
        throw new RuntimeException("Transação não completada");
    }

    public void error() {
        RestResponse<T> response = new RestResponse<T>( false, "error" );
        result.use(json()).withoutRoot().from(response).serialize();
    }
    
    public void error(String msg)
    {
        RestResponse<T> response = new RestResponse<T>( false, msg );
        result.use(json()).withoutRoot().from(response).serialize();
    }

    public void success(List<T> list)
    {
        RestResponse<T> response = new RestResponse<T>( true, list );
        result.use(json()).withoutRoot().from(response).include("list").serialize();
    }

    public void success(T object)
    {
        RestResponse<T> response = new RestResponse<T>( true, object );
        result.use(json()).withoutRoot().from(response).include("object").serialize();
    }

    public void success()
    {
        RestResponse<T> response = new RestResponse<T>( true, (String)null );
        result.use(json()).withoutRoot().from(response).serialize();
    }
    
}
